# -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 12:37:15 2018

@author: JockJo
"""

import json
import zipfile
import xml_util
import os


def parse_zip_file(single_zip):
    xmlutil = xml_util.XMLUTIL()
    with zipfile.ZipFile(single_zip) as zf:
        # print(zf.namelist())
        for single_zip in zf.namelist():          #获取压缩包列表每个文件
            xml_str = zf.read(single_zip).decode('utf-8')   #读取压缩包列表中的xml文件
            #print('file length ', len(xml_str))
            start_str = xml_str[0:38]                        #获取文件中xml头部
            xmls_list = xml_str.split(start_str)             #划分出每个xml文件，存入到列表中

            xml_number = 0
            single_zip_name = single_zip
            single_zip_name = single_zip_name.replace('.xml', '')  # 去除文件后缀
            for xml_str in xmls_list:
                #index = xmls_list.index(xml_str)
                xml_str = start_str + xml_str               #给xml文件加上文件头部
                filename = '{}_{}'.format(single_zip_name, xml_number)
                xmlutil.xmlstr_print(xml_str, filename,single_zip_name)                #将xml文件中的每个xml提取出来输出到文件中
                xml_number += 1
                xml_dict = xmlutil.xml_to_dict(xml_str,filename)                       #输出字符串类型的xml
                jsonstr = json.dumps(xml_dict,indent=4)
                xmlutil.xmljson_print(jsonstr, filename,single_zip_name)               #输出json类型的xml

if __name__ == '__main__':
    xmlutil = xml_util.XMLUTIL()
    rootdir = r'C:\Users\JockJo\Desktop\xml'
    # targetdir = r'C:\Users\JockJo\Desktop\target'
    try:
        for parent,dirnames,filenames in os.walk(rootdir):
            for filename in filenames:
                f = open(rootdir + '\\' + filename, 'r')
                xml_str = f.read()
                xmlutil.xml_to_mongodb(xml_str=xml_str, mongo_db='patent', mongo_collection='USPTO')
                # item = xmlutil.xml_to_mongodb(xml_str)
                # with open(targetdir + '\\' + filename, 'w') as f:
                #     print(item, file=f)
    except Exception as e:
        print(e)
